package com.zhc.excel.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhc.common.monitor.domain.MonitorStrategySetting;
import com.zhc.common.monitor.quartz.QuartzManager;
import com.zhc.common.utils.page.PageUtil;
import com.zhc.common.utils.wrap.WrapMapper;
import com.zhc.common.utils.wrap.Wrapper;
import com.zhc.common.web.controller.base.MonitorBaseController;

/**
 * 说明：监控控制
 * @author jinsicao
 * @version 2017年9月19日
 */
@Controller
@RequestMapping("monitorManager")
public class MonitorManagerController extends MonitorBaseController implements ApplicationListener<ContextRefreshedEvent> {

	/** 视图前缀 */
    private static final String viewPrefix ="monitorManager";
    
    /**
     * 分页 查询数据
     * 
     * @param model
     * @param jobGroup
     * @return
     */
    @RequestMapping(value = "")
    public String index(Model model, String jobGroup) {
        try {
        	List<MonitorStrategySetting> settings = null;
        	if (StringUtils.isNotBlank(jobGroup)) {
        		settings = QuartzManager.newInstance().getJobsByGroup(jobGroup);
        	} else {
        		settings = QuartzManager.newInstance().getAllJobs();
        	}
        	model.addAttribute("jobGroup", jobGroup);
        	model.addAttribute("jobs", settings);
        } catch (Exception e) {
        	logger.error("MonitorManagerController index has error.", e);
        }
        return viewPrefix + "/index";
    }
    
    @RequestMapping(value = "addForward")
    public String addForward() {
        return viewPrefix + "/edit";
    }
    
    @RequestMapping(value = "updateForward")
    public String updateForward(Model model, MonitorStrategySetting setting) {
        try {
            model.addAttribute("setting", super.getJob(setting));
        } catch (Exception e) {
        	logger.error("MonitorManagerController updateForward has error.", e);
        }
        return viewPrefix + "/edit";
    }
    
    @RequestMapping(value = "addOrUpdate")
    @ResponseBody
    public Wrapper<?> addOrUpdate(MonitorStrategySetting setting) {
        try {
            if (QuartzManager.newInstance().addOrUpdateJob(setting)) {
                return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "添加/更新成功！");
            } else {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加/更新失败！");
            }
        } catch (Exception e) {
        	logger.error("MonitorManagerController addOrUpdate has error.", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加/更新失败！");
        }
    }
    
    @RequestMapping(value = "pause")
    @ResponseBody
    public Wrapper<?> pause(MonitorStrategySetting setting) {
    	try {
    		if (QuartzManager.newInstance().pauseJob(setting)) {
    			return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "暂停成功！");
    		} else {
    			return WrapMapper.wrap(Wrapper.ERROR_CODE, "暂停失败！");
    		}
    	} catch (Exception e) {
    		logger.error("MonitorManagerController pause has error.", e);
    		return WrapMapper.error();
    	}
    }
    
    @RequestMapping(value = "resume")
    @ResponseBody
    public Wrapper<?> resume(MonitorStrategySetting setting) {
    	try {
    		if (QuartzManager.newInstance().resumeJob(setting)) {
    			return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "恢复成功！");
    		} else {
    			return WrapMapper.wrap(Wrapper.ERROR_CODE, "恢复失败！");
    		}
    	} catch (Exception e) {
    		logger.error("MonitorManagerController pause has error.", e);
    		return WrapMapper.error();
    	}
    }
    
    @RequestMapping(value = "runOnce")
    @ResponseBody
    public Wrapper<?> runOnce(MonitorStrategySetting setting) {
    	try {
    		if (QuartzManager.newInstance().runOnce(setting)) {
    			return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "执行成功！");
    		} else {
    			return WrapMapper.wrap(Wrapper.ERROR_CODE, "执行失败！");
    		}
    	} catch (Exception e) {
    		logger.error("MonitorManagerController runOnce has error.", e);
    		return WrapMapper.error();
    	}
    }
    
    
    @RequestMapping(value = "startAll")
    @ResponseBody
    public Wrapper<?> startAll() {
    	try {
    		if (QuartzManager.newInstance().startJobs()) {
    			return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "启动成功！");
    		} else {
    			return WrapMapper.wrap(Wrapper.ERROR_CODE, "启动失败！");
    		}
    	} catch (Exception e) {
    		logger.error("MonitorManagerController startAll has error.", e);
    		return WrapMapper.error();
    	}
    }
    
    @RequestMapping(value = "delete")
    @ResponseBody
    public Wrapper<?> delete(MonitorStrategySetting setting) {
        try {
            if (QuartzManager.newInstance().closeJob(setting)) {
                return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "删除成功！");
            } else {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "删除失败！");
            }
        } catch (Exception e) {
        	logger.error("MonitorManagerController delete has error.", e);
            return WrapMapper.error();
        }
    }
    
    /**
     * 分页 查询数据
     * 
     * @param model
     * @param page
     * @param query
     * @return
     */
    @RequestMapping(value = "jobtest")
    public String jobtest(Model model, PageUtil page) {
    	try {
    		MonitorStrategySetting setting = monitorStrategyBuilders.get("exampleGroupType", "baseMonitorExecutor");
    		
    		QuartzManager.newInstance().addOrUpdateJob(setting);
//    		boolean flag = context.doExecute();
//    		
//    		System.out.println(flag);
    	} catch (Exception e) {
    		logger.error("MonitorTestController index has error.", e);
    	}
    	return viewPrefix + "/index";
    }

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// root application context 没有parent，他就是老大.
		if (event.getApplicationContext().getParent() == null) {
			// 需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
			System.out.println("需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。  ");
			super.initJobs();
		}
	}
}
